package com.hroze.util.web;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

/**
 * 本类实现会话过滤，字符过滤（区分后缀）
 * 
 * @author ahoo
 * 
 */
public class CommonFilter implements Filter {
	private Logger log = Logger.getLogger(this.getClass());
	public static Prop CONFIG;

	public void destroy() {
	}

	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain chain) throws IOException, ServletException {

		HttpServletRequest request = (HttpServletRequest) arg0;
		HttpServletResponse response = (HttpServletResponse) arg1;
		String method = request.getMethod();
		String url = request.getRequestURI();
		log.debug(url);
		String header = request.getHeader("X-Requested-With");
		// System.out.println(header);
		if ("XMLHttpRequest".equals(header)) {
			request.setCharacterEncoding("UTF-8");
		} else if (url.indexOf(CONFIG.get("flashEncode", ".flh")) != -1) {
			log.debug("urlDecode-->utf-8");
			WebTool.decodeParams(request, "UTF-8");
		} else {
			log.debug("to--->" + CONFIG.get("encode", "UTF-8"));
			if (method.toUpperCase().equals("POST")) {// post方法
				request.setCharacterEncoding(CONFIG.get("encode", "UTF-8"));
			} else if (method.toUpperCase().equals("GET")) {// get方法
				Enumeration paramNames = request.getParameterNames();
				while (paramNames.hasMoreElements()) {
					String name = paramNames.nextElement().toString();
					String[] values = request.getParameterValues(name);
					if (values != null) {
						for (int i = 0; i < values.length; i++) {
							values[i] = new String(values[i]
									.getBytes("ISO-8859-1"), CONFIG.get(
									"encode", "UTF-8"));
						}
					}
				}
			}

		}
		response.setCharacterEncoding(CONFIG.get("encode", "UTF-8"));
		chain.doFilter(request, response);

	}

	public void init(FilterConfig arg0) throws ServletException {
		CONFIG = new Prop(CommonFilter.class);
	}

	/**
	 * 重新载入配置文件
	 */
	public static void reload() {
		CONFIG.reload();
	}

}
